<template>
  <div>
    <van-search
    :class="{rent_search:move}"
    v-model="value"
    show-action
    placeholder="请输入搜索关键词"
    left-icon="search"
    @cancel="$router.back()"
    @focus="move=false"
    @blur="value ? move=false : move=true"
    @input="loadAreaCommunity"
  />
  <van-cell-group v-if="value">
    <van-cell @click="onAreaCommunity(item.communityName,item.community)" v-for="item in areaCommunityList" :key="item.communityName" :value="item.communityName" />
  </van-cell-group>
  </div>
</template>

<script>
import { getAreaCommunity } from '@/api/city.js'
import { Toast } from 'vant'
export default {
  name: 'RentSearch',
  data () {
    return {
      value: '',
      move: true,
      areaCommunityList: []// 用来保存搜索的联想建议
    }
  },

  created () {

  },

  methods: {
    onAreaCommunity (name, id) {
      this.value = name
      this.$router.push({
        path: '/rent/add',
        query: {
          name,
          id
        }
      })
    },
    // 小区关键词查询
    loadAreaCommunity () {
      if (this.id) {
        clearTimeout(this.id)
      }
      if (this.value === '') return
      // 延时防抖
      this.id = setTimeout(async () => {
        try {
          const res = await getAreaCommunity({
            name: this.value,
            id: this.$store.state.cityInfo.id
          })
          // console.log(res)
          // 保存数据
          this.areaCommunityList = res.data.body
        } catch (err) {
          Toast.fail('网络不佳！')
        }
      }, 700)
    }
  }
}
</script>

<style scoped lang='less'>
.rent_search{
  /deep/.van-field__left-icon{
    flex: 1;
    text-align: right;
  }
  /deep/.van-cell__value{
    flex: 2;
  }
}
</style>
